﻿using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;

namespace DotNetty.Extensions
{
    class UdpHandler : SimpleChannelInboundHandler<DatagramPacket>
    {
        private readonly UdpSocket _udp;

        public UdpHandler(UdpSocket udp)
        {
            _udp = udp;
        }

        protected override void ChannelRead0(IChannelHandlerContext ctx, DatagramPacket packet)
        {
            if (!packet.Content.IsReadable())
            {
                return;
            }

            _udp.Message(packet.Sender, packet.Content.ToBytes());
        }

        public override void ChannelReadComplete(IChannelHandlerContext context) => context.Flush();

        public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {
            context.CloseAsync();
            _udp.Ex(exception);
        }
    }
}
